﻿using Application.Abstractions.Authentication;
using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Gridify;
using Gridify.EntityFramework;
using SharedKernel;

namespace Application.Todos.Get;

internal sealed class GetTodosQueryHandler(
    IApplicationDbContext context, 
    ICurrentUser currentUser)
    : IQueryHandler<GetTodosQuery,PaginatedList<TodoResponse>>
{
    public async ValueTask<Result<PaginatedList<TodoResponse>>> Handle(GetTodosQuery query, CancellationToken cancellationToken)
    {

        IQueryable<TodoResponse> todos =  context.TodoItems
            .Where(todoItem => todoItem.UserId == currentUser.UserId)
            .Select(todoItem => new TodoResponse
            {
                Id = todoItem.Id,
                UserId = todoItem.UserId,
                Description = todoItem.Description,
                Priority = todoItem.Priority,
                DueDate = todoItem.DueDate,
                Labels = todoItem.Labels,
                IsCompleted = todoItem.IsCompleted,
                CreatedAt = todoItem.CreatedAt,
                CompletedAt = todoItem.CompletedAt
            });
        
        Paging<TodoResponse> pagedData = await todos.GridifyAsync(query.GridifyQuery, cancellationToken);

        var pagedResult = PaginatedList<TodoResponse>.Create(
            pagedData.Data.ToList(),
            query.GridifyQuery.Page,
            query.GridifyQuery.PageSize,
            pagedData.Count);

        return Result.Success(pagedResult);
    }
}
